package com.erik.crawler.task;

import com.erik.crawler.model.IpInfo;
import com.erik.crawler.service.ehcache.ProxyEhcache;
import com.erik.crawler.service.proxy.KuaidailiProxyPoolServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@ConfigurationProperties
public class ProxyCrawlTask {

    private static Logger LOGGER = LoggerFactory.getLogger(ProxyCrawlTask.class);

    @Value("${task.crawl.enabled}")
    private Boolean enabled;
    @Autowired
    private ProxyEhcache proxyEhcache;
    @Autowired
    private KuaidailiProxyPoolServiceImpl kuaidailiCrawler;

    /**
     * Capture free proxy regularly
     */
    @Scheduled(initialDelay = 2 * 60 * 1000, fixedDelay = 1 * 60 * 60 * 1000)
    public void crawlProxyScheduale() {

        if (enabled) {

            try {
                long start = System.currentTimeMillis();
                LOGGER.info("=====>>>>>Start crawling Proxy");
                List<String> results = kuaidailiCrawler.crawl();

                if (!CollectionUtils.isEmpty(results)) {
                    IpInfo ipInfo = null;
                    for (String proxy : results) {
                        ipInfo = new IpInfo();
                        //164.115.22.45:8080
                        String[] result = proxy.split(":");
                        ipInfo.setIpStr(result[0]);
                        ipInfo.setPort(result[1]);

                        this.proxyEhcache.save(ipInfo);
                    }
                }
                LOGGER.info("<<<<<=====End of crawling proxy, total time [{}] Ms.", System.currentTimeMillis() - start);
            } catch (Exception e) {
                LOGGER.error("Ooooooops!!!!An exception occurred in the scheduled task of the capture agent", e);
            }
        }

    }


}
